package com.lange.fileManagement.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaGenerator {

    private static final int WIDTH = 200;
    private static final int HEIGHT = 70;
    private static final int CODE_LENGTH = 4;
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public BufferedImage generateCaptcha(String captchaCode) {
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();

        // 设置背景色
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体
        graphics.setFont(new Font("Arial", Font.BOLD, 40));

        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }

        // 绘制验证码字符
        for (int i = 0; i < CODE_LENGTH; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawString(String.valueOf(captchaCode.charAt(i)), 30 + (i * 30), 40 + random.nextInt(10));
        }

        graphics.dispose();
        return bufferedImage;
    }

    public String generateCaptchaCode() {
        StringBuilder captchaCode = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            captchaCode.append(CHARACTERS.charAt(index));
        }
        return captchaCode.toString();
    }

    private Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }
}